package com.efounder.chat.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.SectionIndexer;
import android.widget.TextView;

import com.efounder.chat.R;
import com.efounder.chat.utils.LXGlideImageLoader;
import com.efounder.mobilecomps.contacts.User;
import com.efounder.thirdpartycomps.stickylistheaders.StickyListHeadersAdapter;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * 群聊通讯录adapter ps：数据传入钱需要先进行排序
 *
 * @author yqs
 */
public class SelectContactAdapter extends BaseAdapter implements
        StickyListHeadersAdapter, SectionIndexer {
    private List<User> mList;
    private List<User> existList = new ArrayList<>();
    private ArrayList<User> mSelectedList = new ArrayList<>();
    private ArrayList<String> mSelectedId = new ArrayList<String>();
    public ArrayList<String> mexistId = new ArrayList<String>();//跳到页面时已选中的人
    private Context mContext;
    //是否是单选模式 单选隐藏 选择框
    private boolean isSingleMode = false;
    //isCancleSelected 是否可以取消默认选中的选项
    private boolean isCancleSelected;


    public SelectContactAdapter(Context mContext, List<User> list, List<User> mExistList) {
        this.mContext = mContext;
        mSelectedList.addAll(mExistList);
        //initImageLoader();
        this.existList = mExistList;
        for (int i = 0; i < mSelectedList.size(); i++) {
            mSelectedId.add(String.valueOf(mSelectedList.get(i).getId()));
            mexistId.add(String.valueOf(mSelectedList.get(i).getId()));
        }
        if (list == null) {
            this.mList = new ArrayList<User>();
        } else {
            this.mList = list;
        }
    }


    public void setSingleMode(boolean isSingle) {
        isSingleMode = isSingle;
    }

    public void setCancleSelected(boolean cancleSelected) {
        isCancleSelected = cancleSelected;
        if(cancleSelected){
            mexistId.clear();
        }
    }

    /**
     * 当ListView数据发生变化时,调用此方法来更新ListView
     *
     * @param list
     */
    public void updateListView(List<User> list) {
        this.mList = list;
        notifyDataSetChanged();
    }

    public int getCount() {
        return mList.size();
    }

    public User getItem(int position) {
        return mList.get(position);
    }

    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View view, ViewGroup viewGroup) {
        ViewHolder viewHolder = null;
        final User user = mList.get(position);
        if (view == null) {
            viewHolder = new ViewHolder();
            view = LayoutInflater.from(mContext).inflate(
                    R.layout.select_groupcontacts_item, viewGroup, false);
            viewHolder.text = (TextView) view.findViewById(R.id.title);
            viewHolder.avatar = (ImageView) view.findViewById(R.id.avatar);
            viewHolder.checked = (CheckBox) view.findViewById(R.id.checked);
            view.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) view.getTag();
        }

        if (user.getReMark() == null || user.getReMark().equals("")) {
            viewHolder.text.setText(user.getNickName());
        } else {
            viewHolder.text.setText(user.getReMark());
        }
        LXGlideImageLoader.getInstance().showRoundUserAvatar(mContext, viewHolder.avatar, user.getAvatar()
                , LXGlideImageLoader.DEFATLT_AVATAR_RADIUS_10);

        boolean isBoolean = isSelected(user);
        System.out.println(isBoolean);
        viewHolder.checked.setChecked(isSelected(user));
        if (mexistId.contains(String.valueOf(user.getId()))) {
            // viewHolder.checked.setClickable(false);
            viewHolder.checked.setEnabled(false);
        } else {
            // viewHolder.checked.setClickable(false);
            viewHolder.checked.setEnabled(true);
        }
        if (isSingleMode) {
            viewHolder.checked.setVisibility(View.INVISIBLE);
        } else {
            viewHolder.checked.setVisibility(View.VISIBLE);
        }

        return view;

    }

    @Override
    public View getHeaderView(int position, View convertView, ViewGroup parent) {
        HeaderViewHolder holder;

        if (convertView == null) {
            holder = new HeaderViewHolder();
            convertView = LayoutInflater.from(mContext).inflate(
                    R.layout.contacts_header, parent, false);
            holder.text = (TextView) convertView.findViewById(R.id.header);
            convertView.setTag(holder);
        } else {
            holder = (HeaderViewHolder) convertView.getTag();
        }

        // set header text as first char in name
        CharSequence headerChar = mList.get(position).getSortLetters();
        holder.text.setText(headerChar);
        // 隐藏最顶端headerView
        if ("↑".equals(headerChar)) {
            holder.text.setVisibility(View.GONE);
        } else {
            holder.text.setVisibility(View.VISIBLE);
        }

        return convertView;
    }

    /**
     * 根据ListView的当前位置获取分类的首字母的Char ascii值
     */
    @Override
    public int getSectionForPosition(int position) {
        return mList.get(position).getSortLetters().charAt(0);
    }

    /**
     * 根据分类的首字母的Char ascii值获取其第一次出现该首字母的位置
     */
    @Override
    public int getPositionForSection(int section) {
        for (int i = 0; i < getCount(); i++) {
            String sortStr = mList.get(i).getSortLetters();
            char firstChar = sortStr.toUpperCase(Locale.getDefault()).charAt(0);
            if (firstChar == section) {
                return i;
            }
        }

        return -1;
    }

    @Override
    public Object[] getSections() {
        return mList.toArray();
    }

    @Override
    public long getHeaderId(int position) {
        return mList.get(position).getSortLetters().charAt(0);
    }

    private boolean isSelected(User model) {
        //return mSelectedList.contains(model);
        return mSelectedId.contains(String.valueOf(model.getId()));
        // return true;
    }

    public void toggleChecked(int position) {
        if (isSelected(mList.get(position))) {
            removeSelected(position);
        } else {
            setSelected(position);
        }

    }

    private void setSelected(int position) {
        if (!mSelectedList.contains(mList.get(position))) {
            mSelectedList.add(mList.get(position));
            mSelectedId.add(String.valueOf(((mList.get(position)).getId())));
        }
    }

    private void removeSelected(int position) {
        if (mSelectedList.contains(mList.get(position))) {
            mSelectedList.remove(mList.get(position));
            mSelectedId.remove(String.valueOf(((mList.get(position)).getId())));
        }
    }

    public ArrayList<User> getSelectedList() {
        if(!isCancleSelected){
            mSelectedList.removeAll((ArrayList<User>) existList);
        }
        if (mSelectedList.size() == 0) {
            return mSelectedList;
        } else {
            return mSelectedList;
        }
    }

    class HeaderViewHolder {
        TextView text;
    }

    public static class ViewHolder {
        public TextView text;
        public ImageView avatar;
        public CheckBox checked;
    }
}